<?php
/**
* @file disubjectm.php
* @synopsis  疾病专题
* @author Yee, <rlk002@gmail.com>
* @version 1.0
* @date 2015年7月1日10:50:35
*/

defined('BASEPATH') OR exit('No direct script access allowed');

class Disubjectm extends CI_Model
{
    const GET_ONE_DISUBJECT = "get_one_disubject_";
	function __construct()
	{
        parent::__construct();
	}

	public function get_list($page,$page_size,$uid,$get_thread = 0)
	{
        $start = $page_size*($page-1);
		$data = array();
		//如果没有登陆 返回所有
        if($uid)
		{
            if($get_thread)
            {
                if($get_thread == 'all')
                {
                    $thread = 0;
                }else{
                    $thread = $get_thread;
                }

            }else{
                $this->load->model("userm");
                $userinfo = $this->userm->getUserInfoById($uid,$nocache=1);
                $thread = $userinfo['thread'];
            }
            //如果是医学生或者实习医生 则全部显示
			if($thread != "-1" && $thread != "-2" && $thread != 0)
			{
				$this->db->select("id,title,show_time");
				$where = "is_show=1 and (typeid  like '".$thread.",%' or ( typeid like '%,".$thread.",%' or '%,".$thread.",' or '[0-9]".$thread.",%'))";
				$this->db->where($where);
				//$this->db->order_by("id","desc"); 排序规则改为按显示时间排序
                $this->db->order_by("show_time","desc");
				$result = $this->db->get("ml_disubject_title",$page_size,$start)->result_array();
            }
			else
			{
				$this->db->select("id,title,show_time");
                $this->db->order_by("show_time","desc");
				$this->db->where("is_show",1);
                $this->db->not_like('typeid','2000','both');
				$result = $this->db->get("ml_disubject_title",$page_size,$start)->result_array();
			}

            if ($page == 1) {
                $key = "dissubject_count_" . $uid . '_' . $thread;
                $this->mc->save($key, 0, 20 * 60);
            }
		}
		else
		{
			$this->db->select("id,title,show_time");
            $this->db->order_by("show_time","desc");
            if($get_thread)
            {
                if($get_thread == 'all')
                {
                    $thread = 0;
                }
                else
                {
                    $thread = $get_thread;
                }
                $where = "is_show=1 and (typeid  like '".$thread.",%' or ( typeid like '%,".$thread.",%' or '%,".$thread.",' or '[0-9]".$thread.",%'))";
                $this->db->where($where);
            }else{
                $thread  = 'all';
                $this->db->where("is_show",1);
                $this->db->not_like('typeid','2000','both');
            }
            $result = $this->db->get("ml_disubject_title",$page_size,$start)->result_array();
        }
        #如果返回结果为空 则返回所有专题
        if($thread == "-1" || $thread == "-2" || $thread == 0 ||!$this->is_thread_disubject($thread))
        {
            if($page == 1)
            {
                $get_thread = 'all';
            }
            $this->db->select("id,title,show_time");
            $this->db->order_by("show_time","desc");
            $this->db->where("is_show",1);
            $this->db->not_like('typeid','2000','both');
            $result = $this->db->get("ml_disubject_title",$page_size,$start)->result_array();
        }

		foreach ($result as $key => $value) {
			$item = array();
			$item['id'] = $value['id'];
			$item['title'] = $value['title'];
			$item['show_time'] = $value['show_time'];
            $query = array("did"=>$value['id'],"user_id"=>$this->uid);
            $item['favorite_count'] = $this->get_favorite_count($query);

			# 推荐专题列表信息
            $recmmond_list = $this->get_recmmond_list($value['id']);
            $normal_list = $this->get_normal_list($value['id']);
            //如果推荐列表为空 则拿一个正常的到推荐哪里
            if(count($recmmond_list) == 0)
            {
                //为了兼容1.9.0线上Bug,将正常的第一个换成推荐 正常最后一个放到推荐中去
                $last_item = Array_pop($normal_list);
                $item['recmmond_list']= array($last_item);

                array_unshift($normal_list,$recmmond_list[0]);
                unset($normal_list[0]);
                $new_normal_list = [];//这里需要重新处理下数组 不然数组不是从0开始 IOS会无法显示
                foreach ($normal_list as $key => $value) {
                    $new_normal_list[] = $value;
                }
                $item['normal_list'] = $new_normal_list;
            }
            else
            {
                $item['recmmond_list'] = $recmmond_list;
                $item['normal_list'] = $normal_list;
            }
			$data[] = $item;
		}
        if(version_compare($this->softversion,'2.2.2') >= 0)
        {
              //登录情况下 医学生和实习医生返回全部
              if($thread=='-1'||$thread=='-2')
              {
                  $thread = 'all';
              }
              //客户端传thread 则 返回客户端传的科室
              $thread = $get_thread ? $get_thread : $thread;
              $result = array('thread'=>$thread,'result'=>$data);
              return $result;
        }
		return $data;
	}

	/*获取推荐列表*/
	public function get_recmmond_list($disubject_title_id)
	{
		$this->db->select();
        $this->db->where(array("parent_id"=>$disubject_title_id,"is_recommand"=>1,"is_show"=>1));
        //$this->db->order_by("id","desc");
        $this->db->order_by("sort","asc");
        $ret = $this->db->get("ml_disubject")->result_array();
		$return = array();
        if($ret)
        {
            foreach ($ret as $key => $value) {
                $return[] = $this->get_one_disubject($value['id'],$this->uid);
            }
        }

		return $return;
	}

	/*获取普通列表*/
	public function get_normal_list($disubject_title_id)
	{
		$this->db->select();
        $this->db->where(array("parent_id"=>$disubject_title_id,"is_recommand"=>0,"is_show"=>1));
        //->order_by("id","desc")
        $this->db->order_by("sort","asc");
        $ret =$this->db->get("ml_disubject")->result_array();
		$return = array();
		if($ret)
        {
            foreach ($ret as $key => $value) {
                $return[] = $this->get_one_disubject($value['id'],$this->uid);
            }
        }
		return $return;
	}

	//获取某个用户下的最新专题数
	public function get_disubject_count_by_uid($uid,$where)
	{
		$this->load->model("userm");
		$userinfo = $this->userm->getUserInfoById($uid);
		$thread = $userinfo['thread'];

        $key = "dissubject_count_" . $uid . '_' . $thread;
        $cache = $this->mc->get($key);
        if (is_bool($cache) && $cache == false) {
            $where .= " and is_show=1 and (typeid  like '".$thread.",%' or ( typeid like '%,".$thread.",%' or '%,".$thread.",' or '[0-9]".$thread.",%'))";
            $result = $this->db->where($where)->count_all_results("ml_disubject_title");

            $this->mc->save($key, $result, 20 * 60);
        }
        else {
            $result = $cache;
        }

		return $result;
	}

    /**
     * 获取收藏数
     * @param $did
     * @param $uid
     */
    public function get_favorite_count($query)
    {
        return $result = $this->db->where($query)->count_all_results("ml_disubject_favorite");
    }

    /**
     * 添加专题收藏
     * @param $did
     * @param $uid
     */
    public function insert_favorite($did,$user_id)
    {
        $sets = array(
            "did"       =>  $did,
            "user_id"       =>  $user_id,
            "addtime"   => time()
        );
        return $result = $this->db->insert("ml_disubject_favorite",$sets);
    }


    /**
     * 取消收藏
     * @param $did
     * @param $uid
     * @return mixed
     */
    public function remove_favorite($did,$user_id)
    {
        $query = array(
            "did"   =>  $did,
            "user_id"   =>  $user_id
        );

        if($query)  // 不能为空
        {
            $result = $this->db->where($query)->delete("ml_disubject_favorite");     //只删除一条
            return $result;
        }
    }

    /**
     * 获取我的关注的专题列表
     * @param $user_id
     * @param $start
     * @param $page_size
     * @return array
     */
    public function get_my_favorite_disubject($user_id,$start,$page_size)
    {
        $return = [];
        //首先获取我的收藏的专题列表
        $favorite_disubject_id = $this->db->select("did")->where("user_id",$user_id)->order_by("addtime","desc")->limit($page_size,$start)->get('ml_disubject_favorite')->result_array();

        foreach($favorite_disubject_id as $val)
        {
            $return[] = $this->get_one_disubject($val['did'],$user_id);
        }
        return $return;
    }

    /**
     * 获取一个专题内容
     * @param $did
     * @return mixed
     */
    public function get_one_disubject($did,$user_id = 0)
    {
        $mc = $this->cache->memcached;
        $key = $this->GET_ONE_DISUBJECT.$did;

        if(!$this->cache->memcached->is_supported())
        {
            $result = array("code" => -3,'tips' => "缓存未开启");
        }
        $val = $mc->get($key);
        if(!$val)
        {
            $one_page = $this->db->select()->from('ml_disubject')->where("id",$did)->order_by("id","desc")->get()->result_array();
            $one_page = $one_page[0];
            $val = [];
            $val['id'] = $one_page['id'];
            $val['title'] = $one_page['title'];
            $val['images_thumb'] = ret_fullpath_url($one_page['images_thumb']);
            $val['small_img'] = ret_fullpath_url($one_page['small_img']);
            $val['short_intro'] = $one_page['short_intro'];
            $val['url'] = WEB_URL."disubject/show/".$one_page['id'];

            $mc->save($key,$val, 60*3);
        }
        //收藏数不加入缓存
        if($user_id)
        {
            $query = array("did"=>$did,"user_id"=>$user_id);
            $val['favorite_status'] = $this->get_favorite_count($query);
        }
        else
        {
            $val['favorite_status'] = 0;
        }

        return $val;
    }
    //判断该科室下是否有专题
    public function is_thread_disubject($thread)
    {
        if($thread == 'all')
        {
            return true;
        }
        $where = "is_show=1 and (typeid  like '".$thread.",%' or ( typeid like '%,".$thread.",%' or '%,".$thread.",' or '[0-9]".$thread.",%'))";
        $this->db->select("id");
        $this->db->where($where);
        $result = $this->db->get("ml_disubject_title")->row_array();
        return $result;
    }



}
